The Call Stack and Debugging
Call stack
- A call stack is a mechanism for an interpreter (like the JavaScript interpreter in a web browser) to keep track of its place in a script that calls multiple functions — what function is currently being run and what functions are called from within that function, etc.
function greeting() {
// [1] Some codes here
sayHi();
// [2] Some codes here
}
function sayHi() {
return "Hi!";
}
// Invoke the `greeting` function
greeting();
// [3] Some codes here
- How does the call stack handle function calls?
function firstFunction(){ console.log("Hello from firstFunction");}
function secondFunction(){ firstFunction(); console.log("The end from secondFunction");}
secondFunction();
This is what happens when the code is run:
- When secondFunction() gets executed, an empty stack frame is created. It is the main (anonymous) entry point of the program.
- secondFunction() then calls firstFunction()which is pushed into the stack.
- firstFunction() returns and prints “Hello from firstFunction” to the console.
- firstFunction() is pop off the stack.
- The execution order then move to secondFunction().
- secondFunction() returns and print “The end from secondFunction” to the console.
- secondFunction() is pop off the stack, clearing the memory.
The key takeaways from the call stack are:
- It is single-threaded. Meaning it can only do one thing at a time.
- Code execution is synchronous.
- A function invocation creates a stack frame that occupies a temporary memory.
- It works as a LIFO — Last In, First Out data structure.
Debugging
- Types of error messages
- Reference errors
- Syntax errors
- Range errors
- Type errors
- Debugging